//package com.groupfifteen.controller;
//
//import com.groupfifteen.common.R;
//import com.groupfifteen.entity.SysAdminEntity;
//import com.groupfifteen.entity.SysLoginEntity;
//import com.groupfifteen.entity.SysTeacherEntity;
//import com.groupfifteen.entity.SysUserEntity;
//import com.groupfifteen.service.SysLoginService;
//import com.groupfifteen.util.ApiResultHandler;
//import lombok.RequiredArgsConstructor;
//import org.springframework.web.bind.annotation.PostMapping;
//import org.springframework.web.bind.annotation.RequestBody;
//import org.springframework.web.bind.annotation.RestController;
//
//import javax.servlet.http.Cookie;
//import javax.servlet.http.HttpServletResponse;
//import java.security.MessageDigest;
//import java.security.NoSuchAlgorithmException;
//
//
///**
// * 用户登录 控制层
// *
// */
//@RestController
//@RequiredArgsConstructor
//public class SysLoginController {
//    private final SysLoginService sysLoginService;
//
//    @PostMapping("/login")
//    public R login(@RequestBody SysLoginEntity sysLoginEntity, HttpServletResponse response) {
//        // 参数校验
//        if (sysLoginEntity.getId() == null || sysLoginEntity.getPassword() == null || sysLoginEntity.getPassword().isEmpty()) {
//            return ApiResultHandler.buildApiResult(400, "用户名或密码不能为空", null);
//        }
//
//        try {
//            Integer id = sysLoginEntity.getId();
//            // 对密码进行 SHA - 256 加密
//            String encryptedPassword = encryptWithSHA256(sysLoginEntity.getPassword());
//
//            // 登录管理员
//            SysAdminEntity adminRes = sysLoginService.adminLogin(id, encryptedPassword);
//            if (adminRes != null) {
//                setLoginCookies(response, adminRes.getCardId(), "0");
//                return ApiResultHandler.buildApiResult(200, "请求成功", adminRes);
//            }
//
//            // 登录教师
//            SysTeacherEntity teacherRes = sysLoginService.teacherLogin(id, encryptedPassword);
//            if (teacherRes != null) {
//                setLoginCookies(response, teacherRes.getCardId(), "1");
//                return ApiResultHandler.buildApiResult(200, "请求成功", teacherRes);
//            }
//
//            // 登录学生
//            SysUserEntity studentRes = sysLoginService.userLogin(id, encryptedPassword);
//            if (studentRes != null) {
//                setLoginCookies(response, studentRes.getIdNo(), "2");
//                return ApiResultHandler.buildApiResult(200, "请求成功", studentRes);
//            }
//        } catch (Exception e) {
//            // 异常处理
//            return ApiResultHandler.buildApiResult(500, "服务器异常", null);
//        }
//
//        return ApiResultHandler.buildApiResult(400, "请求失败", null);
//    }
//
//    private String encryptWithSHA256(String password) {
//        try {
//            MessageDigest digest = MessageDigest.getInstance("SHA-256");
//            byte[] encodedhash = digest.digest(password.getBytes());
//            return bytesToHex(encodedhash);
//        } catch (NoSuchAlgorithmException e) {
//            throw new RuntimeException("SHA - 256 algorithm not found", e);
//        }
//    }
//
//    private String bytesToHex(byte[] hash) {
//        StringBuilder hexString = new StringBuilder(2 * hash.length);
//        for (int i = 0; i < hash.length; i++) {
//            String hex = Integer.toHexString(0xff & hash[i]);
//            if(hex.length() == 1) {
//                hexString.append('0');
//            }
//            hexString.append(hex);
//        }
//        return hexString.toString();
//    }
//    /**
//     * 登出
//     *
//     * @param response http response
//     */
//    @PostMapping("/logout")
//    public void logout(HttpServletResponse response) {
//        //清楚cookie里的token信息
//        Cookie token = new Cookie("rb_token", null);
//        token.setPath("/");
//        token.setMaxAge(0);
//        Cookie role = new Cookie("rb_role", null);
//        role.setPath("/");
//        role.setMaxAge(0);
//        response.addCookie(token);
//        response.addCookie(role);
//    }
//
//    private void setLoginCookies(HttpServletResponse response, String tokenValue, String roleValue) {
//        Cookie token = new Cookie("rb_token", tokenValue);
//        token.setPath("/");
//        token.setMaxAge(60 * 60 * 24 * 7); // 设置 Cookie 的过期时间为 7 天，你可以根据实际需求进行调整
//
//        Cookie role = new Cookie("rb_role", roleValue);
//        role.setPath("/");
//        role.setMaxAge(60 * 60 * 24 * 7); // 设置 Cookie 的过期时间与 token 一致
//
//        response.addCookie(token);
//        response.addCookie(role);
//    }
//}
//
//
//
package com.groupfifteen.controller;

import com.groupfifteen.common.R;
import com.groupfifteen.entity.SysAdminEntity;
import com.groupfifteen.entity.SysLoginEntity;
import com.groupfifteen.entity.SysTeacherEntity;
import com.groupfifteen.entity.SysUserEntity;
import com.groupfifteen.service.SysLoginService;
import com.groupfifteen.util.ApiResultHandler;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;


/**
 * 用户登录 控制层
 *
 */
@RestController
@RequiredArgsConstructor
public class SysLoginController {
    private final SysLoginService sysLoginService;
    @PostMapping("/login")
    public R login(@RequestBody SysLoginEntity sysLoginEntity, HttpServletResponse response) {
        Integer id = sysLoginEntity.getId();
        String password = sysLoginEntity.getPassword();
//登录管理员
        SysAdminEntity  adminRes = sysLoginService.adminLogin(id, password);
        if (adminRes != null) {
            Cookie token = new Cookie("rb_token", adminRes.getCardId());
            token.setPath("/");
            Cookie role = new Cookie("rb_role", "0");
            role.setPath("/");

            //将cookie对象加入response响应
            response.addCookie(token);
            response.addCookie(role);

            return ApiResultHandler.buildApiResult(200, "请求成功", adminRes);
        }

        //登录教师
        SysTeacherEntity teacherRes = sysLoginService.teacherLogin(id, password);
        if (teacherRes != null) {
            Cookie token = new Cookie("rb_token", teacherRes.getCardId());
            token.setPath("/");
            Cookie role = new Cookie("rb_role", "1");
            role.setPath("/");
            response.addCookie(token);
            response.addCookie(role);
            return ApiResultHandler.buildApiResult(200, "请求成功", teacherRes);
        }


//登录学生
        SysUserEntity studentRes = sysLoginService.userLogin(id, password);
        if (studentRes != null) {
            Cookie token = new Cookie("rb_token", studentRes.getIdNo());
            token.setPath("/");
            Cookie role = new Cookie("rb_role", "2");
            role.setPath("/");
            response.addCookie(token);
            response.addCookie(role);
            return ApiResultHandler.buildApiResult(200, "请求成功", studentRes);
        }

        return ApiResultHandler.buildApiResult(400, "请求失败", null);
    }

    /**
     * 登出
     *
     * @param response http response
     */
    @PostMapping("/logout")
    public void logout(HttpServletResponse response) {
        //清楚cookie里的token信息
        Cookie token = new Cookie("rb_token", null);
        token.setPath("/");
        token.setMaxAge(0);
        Cookie role = new Cookie("rb_role", null);
        role.setPath("/");
        role.setMaxAge(0);
        response.addCookie(token);
        response.addCookie(role);
    }


}